import { Actions } from 'react-native-router-flux'
import { DeviceEventEmitter, View } from 'react-native'

import { HOST } from '../config/index'
import { LOGIN_TOKEN } from '../redux/constants/loginTypes'

/**
 * 发送网络请求
 * @param method            HTTP 请求方法
 * @param url               URL
 * @param bodyParams        HTTP Body
 * @param urlParams         URL Params
 */
let isLogining = false
export default async function(
	method,
	url,
	{ bodyParams = {}, urlParams = {}, headersParams = {} }
) {
	const headers = new Headers()
	let h = {
		'Content-Type': 'application/json'
	}
	h = { ...h, ...headersParams }
	for (let i in h) {
		if (h.hasOwnProperty(i)) {
			headers.append(i, h[i])
		}
	}

	let token = ''
	// 获取存储Token
	try {
		token = await global.storage.load({
			key: LOGIN_TOKEN
		})
	} catch (e) {
		console.log('token load err', e)
	}
	
	if (token.length) {
		headers.append('token', token)
	} else {
		loginHandle()
	}
	// 将url参数写入URL
	let urlParStr = ''
	const urlParArr = Object.keys(urlParams)
	if (urlParArr.length) {
		Object.keys(urlParams).forEach(element => {
			urlParStr += `${element}=${urlParams[element]}&`
		})
		urlParStr = `?${urlParStr}`.slice(0, -1)
	}

	const params = {
		method,
		headers
	}
	if (method !== 'GET' && method !== 'HEAD') {
		params.body = JSON.stringify(bodyParams)
	}
	return fetch(new Request(`${HOST}${url}${urlParStr}`, params))
		.then(response => response.json())
		.then(data => {
			if (data.status < 200 || data.status > 299) {
// 				Actions.error({
// 					err: data && data.message
// 				})
			} else {
				if (data.code === '10001') {
					loginHandle()
				}
				if (data.code === '10000') {
					DeviceEventEmitter.emit('forbid.user')
				}
			}
			return data
		})
		.catch(err => {
// 			Actions.error({
// 				err: err && err.message
// 			})
		})
}

function loginHandle() {
	if (!isLogining) {
		isLogining = true
		Actions.login()
	}
}

DeviceEventEmitter.addListener('login.success', () => {
	isLogining = false
})
